package com.ccc.boot.redis.config;

import cn.hutool.core.util.NumberUtil;
import com.ccc.boot.redis.constant.RedisConstant;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.util.StringUtils;

import java.time.Duration;

/**
 * 自定义RedisCacheManager
 *
 * @author superC
 * @version 0.1.0
 * @date 2022/4/8
 */

public class MyRedisCacheManager extends RedisCacheManager {

    public MyRedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration) {
        super(cacheWriter, defaultCacheConfiguration);
    }

    /**
     * 用于在value后加标识符#，进行自定义过期时间设置。
     *      例：@Cacheable(value = "get#60", key = "#id") 表示设定过期时间为60秒
     */
    @Override
    protected RedisCache createRedisCache(String name, RedisCacheConfiguration cacheConfig) {
        if (!StringUtils.isEmpty(name) && name.contains(RedisConstant.MARK)) {
            String cacheName = name.split(RedisConstant.MARK)[0];
            // 默认单位为秒
            String second = name.split(RedisConstant.MARK)[1];
            if (NumberUtil.isInteger(second)) {
                return super.createRedisCache(cacheName, cacheConfig.entryTtl(Duration.ofSeconds(Integer.parseInt(second))));
            }
        }
        // 不包含则走默认时间
        return super.createRedisCache(name, cacheConfig);
    }

}
